﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenLibrary.SpecFLow.Helpers;
using TechTalk.SpecFlow;
using WatiN.Core;
using Table = TechTalk.SpecFlow.Table;

namespace OpenLibrary.SpecFLow.Steps
{
    [Binding]
    public class CreateANewPublisherSteps
    {
        [Given(@"I am logged into the site as an administrator")]
        public void GivenIAmLoggedIntoTheSiteAsAnAdministrator()
        {
            Browsers.Current.GoTo("http://localhost:1031/Account/Login");

            Browsers.Current.TextField(Find.ByName("UserName")).TypeText("admin");
            Browsers.Current.TextField(Find.ByName("Password")).TypeText("123456");
            Browsers.Current.Button(Find.ByValue("Log in")).Click();

            Assert.IsTrue(Browsers.Current.Link(Find.ByText("Log off")).Exists);
        }

        [When(@"I clicked the ""(.*)"" link")]
        public void WhenIClickedTheLink(string linkName)
        {
            var link = Browsers.Current.Link(Find.ByText(linkName));

            if (!link.Exists)
                Assert.Fail(string.Format("Could not find {0} link on the page", linkName));

            link.Click();
        }
        
        [When(@"I entered the following information")]
        public void WhenIEnteredTheFollowingInformation(Table table)
        {
            foreach (var tableRow in table.Rows)
            {
                var publisher = Browsers.Current.TextField(Find.ByName(tableRow["Publisher"]));

                if (!publisher.Exists)
                    Assert.Fail(string.Format("Could not find {0} field on the page", publisher));

                publisher.TypeText(tableRow["Value"]);
            }
        }

        [When(@"I click the ""(.*)"" button")]
        public void WhenIClickTheButton(string buttonValue)
        {
            var button = Browsers.Current.Button(Find.ByValue(buttonValue));

            if (!button.Exists)
                Assert.Fail(string.Format("Could not find {0} button on the page", buttonValue));

            button.Click();
        }
        
        [Then(@"I should see the following details on the screen:")]
        public void ThenIShouldSeeTheFollowingDetailsOnTheScreen(Table table)
        {
            foreach (var tableRow in table.Rows)
            {
                var value = tableRow["Value"];

                Assert.IsTrue(Browsers.Current.ContainsText(value),
                    string.Format("Could not find text '{0}' on the page", value));
            }
        }
    }
}
